#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define SIZE 512
#define ZERO '\0'
#define NUM 32
#define SEP " "

const char* getusername()
{
  const char* name = getenv("USER");
  if(name == NULL) return "none";
  return name;
}

const char* gethostname()
{
  const char* hostname = getenv("HOSTNAME");
  if(hostname == NULL) return "none";
  return hostname;
}

const char* getcwd()
{
  const char* cwd = getenv("PWD");
  if(cwd == NULL) return "none";
  return cwd;
}

void makecommandline()
{
  char line[SIZE];
  const char* username = getusername();
  const char* hostname = gethostname();
  const char* cwd = getcwd();
  
  snprintf(line, sizeof(line), "[%s@%s %s]* ", username, hostname, cwd);
  printf("%s", line);
  fflush(stdout);
}

int getusercommand(char command[], size_t n)
{

  char *s = fgets(command, n, stdin);
  command[strlen(command) - 1] = ZERO;
  if(s == NULL) return -1;

  return strlen(command);
}

char *gArgv[NUM];

void splitcommand(char command[], size_t n)
{
  //ls - a -l -n
  gArgv[0] = strtok(command, SEP);
  int index = 1;
  while(gArgv[index++] = strtok(NULL, SEP));

}
void executecommand()
{
  pid_t id = fork();
  if(id < 0) exit(1);
  else if(id == 0)
  {
    //child
    execvp(gArgv[0], gArgv);
    exit(errno);
  }
  else
  {
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid > 0)
    {

    }
  }
}

int main()
{
  int quit = 1;
    while(quit){
    //自己输出一个命令行
    makecommandline();

    //获取用户命令
    char usercommand[SIZE];
    getusercommand(usercommand, sizeof(usercommand));
    
    //命令行字符分割，分割符是空格
    splitcommand(usercommand, sizeof(usercommand));

    executecommand();
    //执行命令
  }
  return 0;
}
